//
//  JXLocalPushManager.m
//

#import "JXLocalPushManager.h"

#import "JXChatViewController.h"

#define JXLocalPush @"localPush"

@interface JXLocalPushManager ()<JXClientDelegate> {
    NSInteger unreadNum;
}

@property(nonatomic, strong) UIView *localPushView;

@end

@implementation JXLocalPushManager


+ (JXLocalPushManager *)sharedInstance {
    static JXLocalPushManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[JXLocalPushManager alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    if (self = [super init]) {
        unreadNum = 0;
        [[JXIMClient sharedInstance].chatManager addDelegate:self];
    }
    return self;
}

- (UIView *)localPushView {
    if (_localPushView == nil) {
        _localPushView = [[NSBundle mainBundle] loadNibNamed:@"localPushView" owner:nil options:nil].lastObject;
        UIWindow *window = [UIApplication sharedApplication].delegate.window;
        _localPushView.frame = CGRectMake(0, -65, [UIScreen mainScreen].bounds.size.width, 65);
        UITapGestureRecognizer *tapGestureReconizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(localPushViewDidClick:)];
        [_localPushView addGestureRecognizer:tapGestureReconizer];
        [window addSubview:_localPushView];

    }
    return _localPushView;
}

- (void)localPushViewDidClick:(UITapGestureRecognizer *)tapGestureRecognizer {
    //获得当前页面
    UIViewController *currentVC = [self topViewController];
    if (![currentVC isKindOfClass:[JXChatViewController class]]) {
        JXWorkgroup *service = [[JXIMClient sharedInstance].mcsManager activeService];
        if (service) {
//            JXChatViewController *chatVC = [[JXChatViewController alloc] init];
//            chatVC.hidesBottomBarWhenPushed = YES;
//            chatVC.to = service;
//            chatVC.indexPath = _indexPath;
//            [currentVC.navigationController pushViewController:chatVC animated:YES];
        }
    }
}

//注册本地推送
- (void)registerLocalNotification: (UIApplication *)application {
    if([application respondsToSelector:@selector(registerUserNotificationSettings:)]){
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
    }
}

//接收到本地通知的回调
- (void)didReceiveLocalNotification:(UILocalNotification *)notification {
    if (notification.alertBody == nil) {
        return;
    }
    if (![[self topViewController] isKindOfClass:[JXChatViewController class]] && [UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        UILabel *label = [self.localPushView viewWithTag:3];
        label.text = notification.alertBody;
        AudioServicesPlayAlertSound(kSystemRemindVoiceTypeMessage);
        [UIView animateWithDuration:0.5 delay:0.5 options:UIViewAnimationOptionTransitionFlipFromTop animations:^{
            self.localPushView.transform = CGAffineTransformMakeTranslation(0, 65);
        } completion:^(BOOL finished) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [UIView animateWithDuration:0.5 animations:^{
                    self.localPushView.transform = CGAffineTransformIdentity;
                }];
            });
        }];
    }
}



// 刷新iconBadgeNum
- (void)resetApplicationIconBadgeNumber:(UIApplication *)application {
    
    application.applicationIconBadgeNumber = 0;
    // 获得 UIApplication
    UIApplication *app = [UIApplication sharedApplication];
    unreadNum = 0;
    //获取本地推送数组
    NSArray *localArray = [app scheduledLocalNotifications];
    if (localArray) {
        for (UILocalNotification *noti in localArray) {
            [app cancelLocalNotification:noti];
        }
    }
}

- (void)scheduleLocalNotificationWithSession:(id)session {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //本地推送
        UILocalNotification *notification = [[UILocalNotification alloc]init];
        NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:1];
        if (notification != nil) {
            notification.fireDate = pushDate;
            notification.timeZone = [NSTimeZone defaultTimeZone];
            notification.repeatInterval = kCFCalendarUnitDay;
            notification.alertBody = @"客服回呼";
            notification.userInfo = @{JXLocalPush:session};
            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        }
    });
}

- (void)scheduleLocalNotificationWithMessage:(JXMessage *)message{
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground || ![[self topViewController] isKindOfClass:[JXChatViewController class]]) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //本地推送
            UILocalNotification *notification = [[UILocalNotification alloc]init];
            NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:1];
            if (notification != nil) {
                notification.fireDate = pushDate;
                notification.timeZone = [NSTimeZone defaultTimeZone];
                notification.repeatInterval = kCFCalendarUnitDay;
                switch (message.type) {
                    case JXMessageTypeText:
                        notification.alertBody = [NSString
                                stringWithFormat:
                                        @"%@ : %@", message.sender,
                                        [NSString convertToSystemEmoji:message.textToDisplay]];
                        break;
                    case JXMessageTypeImage:
                        notification.alertBody = [NSString stringWithFormat:@"%@发来一条图片消息",message.sender];
                        break;
                    case JXMessageTypeAudio:
                        notification.alertBody = [NSString stringWithFormat:@"%@发来一条音频消息",message.sender];
                        break;
                    case JXMessageTypeVideo:
                        notification.alertBody = [NSString stringWithFormat:@"%@发来一条视频消息",message.sender];;
                        break;
                    default:
                        break;
                }
                unreadNum++;
                notification.applicationIconBadgeNumber = unreadNum;
                [[UIApplication sharedApplication] scheduleLocalNotification:notification];
            }
        });
    }
}


- (void)pushLocalNotification: (UILocalNotification *)notification userInfo: (NSDictionary *)userInfo alertBody: (NSString *)alertBody {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //本地推送
        NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:0];
        if (notification != nil) {
            notification.fireDate = pushDate;
            notification.timeZone = [NSTimeZone defaultTimeZone];
            notification.repeatInterval = kCFCalendarUnitDay;
            notification.soundName = UILocalNotificationDefaultSoundName;
            notification.alertBody = alertBody;
            notification.userInfo = userInfo;
            unreadNum++;
            notification.applicationIconBadgeNumber = unreadNum;
            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        }
    });
}

#pragma mark- JXChatManagerDelegate
- (void)didReceiveMessage:(JXMessage *)message {
    if ([[self topViewController] isKindOfClass:[UIAlertController class]]) {
        return;
    }
    if (![[self topViewController] isKindOfClass:[JXChatViewController class]]) {
        [[JXLocalPushManager sharedInstance] scheduleLocalNotificationWithMessage:message];
    }
}

- (UIViewController*)topViewController {
    return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}

@end
